﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.ComponentModel;
using System.Web.Mvc;

namespace SpeadFrm.Common
{
    public static class CommonEnu
    {

        public static DataTable GetList(Type t)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Value", typeof(string));//值

            dt.Columns.Add("Text", typeof(string));//文本
            dt.PrimaryKey = new DataColumn[] { dt.Columns["Value"] };//主键

            FieldInfo[] fields = t.GetFields();
            foreach (FieldInfo fi in fields)
            {
                if (fi.GetCustomAttributes(false).Length > 0)
                    dt.Rows.Add(new string[] { fi.GetRawConstantValue().ToString(), ((DescriptionAttribute)fi.GetCustomAttributes(false)[0]).Description });
            }
            return dt;
        }

        public static List<SelectListItem> GetSelectList(Type t)
        {
            var fields = t.GetFields();
            var list = fields.Where(c => c.GetCustomAttributes(false).Length > 0)
                .Select(c =>
                        new SelectListItem
                            {
                                Value = c.GetRawConstantValue().ToString(),
                                Text = ((DescriptionAttribute)c.GetCustomAttributes(false)[0]).Description
                            })
                .ToList();
            return list;
        }


        /// <summary>
        /// 通过代码值获取描述 
        /// </summary>
        /// <param name="t"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetDescription(Type t, string code)
        {
            FieldInfo[] fields = t.GetFields();
            foreach (FieldInfo fi in fields)
            {
                if (fi.GetRawConstantValue().Equals(code) && fi.GetCustomAttributes(false).Length > 0)
                    return ((DescriptionAttribute)fi.GetCustomAttributes(false)[0]).Description;
            }
            return string.Empty;
        }
    }
}
